// 云函数入口文件
const cloud = require('wx-server-sdk')
const mysql = require('mysql2/promise')
cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var moblie = event.phone;

  try {
    const connection = await mysql.createConnection({
      host: "47.115.22.254",
      port: 3306,
      database: "EPMS",
      user: "root",
      password: "1234"
    })

    var [rows, a] = await connection.execute('SELECT * FROM OUTPEOPLE WHERE phone="' + moblie +'";');
    //判断数据表中是否有此用户userid，没有则生成插入数据库并返回userid
    if(rows.length == 0){
      var [lastid, a] = await connection.execute('SELECT id FROM OUTPEOPLE ORDER BY id DESC LIMIT 1 ;');
      var userid = lastid[0].id +10000
      var sql = 'INSERT INTO OUTPEOPLE(userid,name,phone) VALUES("' + userid + '","' + userid + '","' + moblie + '");';
      await connection.execute(sql);
      //添加成功返回
      return userid
    }else{
      return rows[0].userid
    } 
    conection.end();
  } catch (err) {
    return err
  }
}